import com.hp.hpl.jena.query.*;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.sparql.resultset.*;

import java.util.*;
import java.io.*;
//import java;

public class QueryEngine {
	
	public String readQuery(String targetFile) throws IOException{
		
		//File queryFile = new File(targetFile);
		
		BufferedReader reader = new BufferedReader(new FileReader(targetFile));
		int readNumber = 0;
		char[] tA = new char[1024];
		StringBuffer queryBuffer = new StringBuffer(1000);
		String qString;
		
		try {
			
			while ( (readNumber = reader.read(tA)) != -1){
		    
					qString = String.valueOf(tA, 0, readNumber);
					queryBuffer.append(qString);
					tA = new char[1024];
			}
			
			reader.close();
			
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//System.out.println(queryBuffer.toString());
		return queryBuffer.toString();
		
		
		//QueryExecution qe = QueryExecutionFactory.create();
		
	}
	
	public void runQuery(String queryString,Model model){
		
		Query query = QueryFactory.create(queryString);
		//System.out.println(query.toString()) ;
		QueryExecution qe = QueryExecutionFactory.create(query, model);
		ResultSet results = qe.execSelect();
		
		
//		RDFNode x = null;
//		Resource r = null;
//		while (results.hasNext())
//	    {
//	      QuerySolution soln = results.next() ;
//	      x = soln.get("w") ;       // Get a result variable by name.
//	      r = soln.getResource("w") ; // Get a result variable - must be a resource
//	      //Literal l = soln.getLiteral("w") ;// Get a result variable - must be a literal
//	      int m;
//	    }
//		System.out.println(r.getLocalName());
		
		
        ResultSetFormatter.out(System.out,results,query);
		qe.close();
	}

}
